package com.Action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.Entity.Users;

public class CkeditorUpload{
	
	private static final Logger logger = Logger.getLogger(CkeditorUpload.class);

	private File upload;  //文件
	private String uploadContentType;  //文件类型
	private String uploadFileName;   //文件名
	
	
	public String excuteImage() throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
      //对文件进行校验  
        if(upload==null || uploadContentType==null || uploadFileName==null){
            out.print("<font color=\"red\" size=\"2\">*请选择上传文件</font>");
            return null;
        }  
        if ((uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg"))  
                && uploadFileName.substring(uploadFileName.length() - 4).toLowerCase().equals(".jpg")) {  
            //IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg  
        }else if(uploadContentType.equals("image/png") && uploadFileName.substring(uploadFileName.length() - 4).toLowerCase().equals(".png")){  
              
        }else if(uploadContentType.equals("image/gif") && uploadFileName.substring(uploadFileName.length() - 4).toLowerCase().equals(".gif")){  
              
        }else if(uploadContentType.equals("image/bmp") && uploadFileName.substring(uploadFileName.length() - 4).toLowerCase().equals(".bmp")){  
              
        }else{
            out.print("<font color=\"red\" size=\"2\">*文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）</font>");  
            return null;  
        }  
          
        if(upload.length() > 5*1024*1024){  
            out.print("<font color=\"red\" size=\"2\">*文件大小不得大于5M</font>");  
            return null;
        }  
        /*
         * 获取当前session，用于创建保存用户图片、文件的路径  
         */
        Users user= (Users) ServletActionContext.getRequest().getSession().getAttribute("temploginbean");
        /**
         * 将文件保存到项目目录下  
         */
        String uploadPath;
		String fileName;
		try {
			InputStream is = new FileInputStream(upload);
			uploadPath = ServletActionContext.getServletContext().getRealPath("\\images\\clubUpload_img")+"\\"+user.getUserId()+"\\topicImg";
			File dirFile = new File(uploadPath);
			/*
			 * 判断当前文件夹（路径）是否存在，如果不存在则创建
			 */
	        if (!dirFile.exists()) {
	        	dirFile.mkdirs();
	        }
	        //为文件重命名
			fileName = java.util.UUID.randomUUID().toString();
			fileName += uploadFileName.substring(uploadFileName.length() - 4);  
			File toFile = new File(uploadPath, fileName);
			logger.info("uploadPath="+uploadPath+"\\"+fileName);
			OutputStream os = new FileOutputStream(toFile);
			byte[] buffer = new byte[1024];
			int length = 0;  
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);     
			}     
			is.close();
			os.close();
			
			//设置返回“图像”选项卡  
	        String callback = ServletActionContext.getRequest().getParameter("CKEditorFuncNum");   
	        out.println("<script type=\"text/javascript\">");  
	        String callbackImgPath="images/clubUpload_img/"+user.getUserId()+"/topicImg/";
	        logger.info("callbackImgPath:---------"+callbackImgPath+fileName);
	        out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" + callbackImgPath + fileName + "','')");    
	        out.println("</script>");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
          
        return null;  
    }  
        
	
	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
}
